package com.citycloud.ccuap.tc.admin.config;

import com.citycloud.ccuap.commons.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

import java.nio.charset.StandardCharsets;

@Slf4j
public class Auth2ResponseExceptionTranslator implements WebResponseExceptionTranslator {
    private final SecurityConfig.SecurityOauth2ClientConfig clientConfig;

    public Auth2ResponseExceptionTranslator(final SecurityConfig.SecurityOauth2ClientConfig clientConfig) {
        this.clientConfig = clientConfig;
    }

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) {
        log.error("Auth2异常", e);
        log.error("clientConfig.getUserLogout():{}", clientConfig.getUserLogout());
        Throwable throwable = e.getCause();
        if (throwable instanceof OAuth2Exception) {
            OAuth2Exception exception = (OAuth2Exception) throwable;

            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType = new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8);
            headers.setContentType(mediaType);

            HttpStatus httpStatus = HttpStatus.resolve(exception.getHttpErrorCode());
            if (httpStatus == null) {
                httpStatus = HttpStatus.OK;
            }

            return new ResponseEntity(JSONUtil.getErrorJSONString((long) exception.getHttpErrorCode(), exception.getLocalizedMessage(), clientConfig.getUserLogout()), headers, httpStatus);
        }
        return new ResponseEntity(JSONUtil.getErrorJSONString((long) HttpStatus.METHOD_NOT_ALLOWED.value(), e.getMessage(), clientConfig.getUserLogout()), HttpStatus.METHOD_NOT_ALLOWED);
    }


}
